package com.mongodb.pool;

import java.util.Arrays;

import com.mongodb.MongoClientSettings;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;

/**
 * @描述 mongoDB连接工具类
 * @author yegucheng
 * @version 1.0.0
 * @date 2018-12-14
 *
 */
public class MongoDriver {
	public static MongoClient mongoClient = null;

	private static final String ADDRESS = "mongodb://localhost:27017";
	private static final String USERNAME = "Name";
	private static final char[] PASSWORD = {};
	private static final String HOST = "127.0.0.1";
	private static final Integer PORT = 27017;
	private static final String DATABASE = "mongo";

	static {
		getClient();
	}

	private static MongoClient getClient() {
		if (mongoClient == null) {
			// ——————————↡ 单机版 ↡----------
			// mongoClient = MongoClients.create(ADDRESS);

			// ——————————↡ 权限控制版 ↡----------
			// 可以使用MongoClientSettings指定TLS/SSL和MongoCredential身份验证信息
			// MongoCredential credential = MongoCredential.createCredential(USERNAME,DATABASE, PASSWORD);
			MongoClientSettings settings = MongoClientSettings.builder()
					// .credential(credential)
					.applyToClusterSettings(builder -> builder.hosts(Arrays.asList(new ServerAddress(HOST, PORT))))
					.build();
			mongoClient = MongoClients.create(settings);
		}
		return mongoClient;
	}
}
